package com.example.hospital.mapper;

import com.example.hospital.domain.entity.DoctorSchedule;
import org.apache.ibatis.annotations.*;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface DoctorScheduleMapper {
    @Insert("INSERT INTO doctor_schedule (doctor_id, schedule_date, time_period, status) VALUES (#{doctorId}, #{scheduleDate}, #{timePeriod}, #{status})")
    @Options(useGeneratedKeys = true, keyProperty = "scheduleId")
    int insert(DoctorSchedule schedule);

    @Update("UPDATE doctor_schedule SET doctor_id=#{doctorId}, schedule_date=#{scheduleDate}, time_period=#{timePeriod}, status=#{status} WHERE schedule_id=#{scheduleId}")
    int update(DoctorSchedule schedule);

    @Delete("DELETE FROM doctor_schedule WHERE schedule_id=#{scheduleId}")
    int delete(@Param("scheduleId") Long scheduleId);

    @Select("SELECT * FROM doctor_schedule WHERE schedule_id=#{scheduleId}")
    DoctorSchedule findById(@Param("scheduleId") Long scheduleId);

    @Select({
            "<script>",
            "SELECT * FROM doctor_schedule",
            "<where>",
            "  <if test=\"doctorId != null\"> AND doctor_id = #{doctorId} </if>",
            "  <if test=\"scheduleDate != null\"> AND schedule_date = #{scheduleDate} </if>",
            "</where>",
            "ORDER BY schedule_date DESC, time_period ASC",
            "LIMIT #{limit} OFFSET #{offset}",
            "</script>"
    })
    List<DoctorSchedule> list(@Param("doctorId") Long doctorId,
                              @Param("scheduleDate") LocalDate scheduleDate,
                              @Param("limit") int limit,
                              @Param("offset") int offset);

    @Select({
            "<script>",
            "SELECT COUNT(1) FROM doctor_schedule",
            "<where>",
            "  <if test=\"doctorId != null\"> AND doctor_id = #{doctorId} </if>",
            "  <if test=\"scheduleDate != null\"> AND schedule_date = #{scheduleDate} </if>",
            "</where>",
            "</script>"
    })
    long count(@Param("doctorId") Long doctorId,
               @Param("scheduleDate") LocalDate scheduleDate);
}